package com.mszlu.blog.admin.service;

import com.mszlu.blog.admin.pojo.Admin;
import com.mszlu.blog.admin.pojo.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Administrator
 * 权限实现类
 */
@Service
public class AuthService {

    @Resource
    private AdminService adminService;

    /**
     * 权限认证
     * @param request 请求
     * @param authentication 验证
     * @return 认证结果
     */
    public boolean auth(HttpServletRequest request, Authentication authentication){
        //请求路径
        String requestURI = request.getRequestURI();
        //当前用户信息 principal
        Object principal = authentication.getPrincipal();
        //判断用户是否登录 或者匿名用户
        if (principal == null || "anonymousUser".equals(principal)){
            //未登录
            return false;
        }
        //用户详情
        UserDetails userDetails = (UserDetails) principal;
        //用户名
        String username = userDetails.getUsername();
        //查找管理员
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null){
            return  false;
        }
        //超级管理员  所有放行
        if (1 == admin.getId()){
            //超级管理员
            return true;
        }
        //管理员id
        Long id = admin.getId();
        //查询权限列表
        List<Permission> permissionList = this.adminService.findPermissionByAdminId(id);
        //去掉路径传参中的问号
        requestURI = StringUtils.split(requestURI,'?')[0];
        for (Permission permission : permissionList) {
            //遍历权限中路径是否匹配
            if (requestURI.equals(permission.getPath())){
                return true;
            }
        }
        return false;
    }
}
